package com.jinzihan.web;

import com.jinzihan.entity.Manager;
import com.jinzihan.service.ManagerService;
import com.jinzihan.service.impl.ManagerServiceImpl;
import com.jinzihan.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ManagerServlet extends BaseServlet{
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = (String) req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        req.getSession().invalidate();

        ManagerService managerService = new ManagerServiceImpl();
        Manager manager = WebUtils.copyParamToBean(req.getParameterMap(), new Manager());
        Manager loginManager = managerService.login(manager);
        String code = req.getParameter("code");

        if ( token!=null && code.equalsIgnoreCase(token) ){
            if (loginManager == null) {
                req.setAttribute("msg","用户名或密码错误");
                String username = req.getParameter("username");
                req.setAttribute("username",username);
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            } else {
                System.out.println("登陆成功");
                req.getSession().setAttribute("manager", manager );
                req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
            }
        }else {
            req.setAttribute("msg","验证码错误");
            String username = req.getParameter("username");
            req.setAttribute("username",username);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }


    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }
}
